//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  ActivityDetailBoard.m
//  iHeima
//
//  Created by he chao on 6/4/14.
//  Copyright (c) 2014 leon. All rights reserved.
//

#import "ActivityDetailBoard.h"
#import "AddActivityBoard.h"
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

#pragma mark -

@interface ActivityDetailBoard()<UIWebViewDelegate>
{
	//<#@private var#>
    
    BeeUIWebView* _webView;
    
    
    NSString* currentUrl;
    
    NSString* _action;
    NSString* _id;
    BOOL _couldChange;
   // BOOL isShoudToNew;
    
    NSString* _afterAddingUrl;
    
}
@end

@implementation ActivityDetailBoard
DEF_SIGNAL(ADD_IN)
DEF_SIGNAL(COLLECTION)
DEF_SIGNAL(SHARE)

- (void)load
{
}

- (void)unload
{
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"活动详情";
    [self showBarButton:BeeUINavigationBar.LEFT image:IMAGESTRING(@"navi_back")];
    [self showNaviBar];
    [self loadContent];
    
   
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if (!btnCollection) {
        btnCollection = [BeeUIButton spawn];
        btnCollection.frame = CGRectMake(self.viewWidth-2*44, 0, 44, 44);
        //[btnCollection setImage:IMAGESTRING(@"navi_collection_gray") forState:UIControlStateNormal];
        [btnCollection addSignal:ActivityDetailBoard.COLLECTION forControlEvents:UIControlEventTouchUpInside];
     //   [btnCollection addTarget:self action:@selector(changeSelect:) forControlEvents:UIControlEventTouchUpOutside];
        
        
    }
    [btnCollection setImage:[self.dictActivity[@"is_faved"] boolValue]?IMAGESTRING(@"navi_collection"):IMAGESTRING(@"navi_collection_gray") forState:UIControlStateNormal];
    [self.navigationController.navigationBar addSubview:btnCollection];
    
    if (!btnShare) {
        btnShare = [BeeUIButton spawn];
        btnShare.frame = CGRectMake(self.viewWidth-44, 0, 44, 44);
        [btnShare setImage:IMAGESTRING(@"navi_share_gray") forState:UIControlStateNormal];
        [btnShare addSignal:ActivityDetailBoard.SHARE forControlEvents:UIControlEventTouchUpInside];
        
        
    }
    [self.navigationController.navigationBar addSubview:btnShare];
}




ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
    [btnCollection removeFromSuperview];
    [btnShare removeFromSuperview];
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
    _couldChange = NO;
    
    
    NSString* currentTitle = self.title;
    if ([currentTitle isEqualToString:@"个人详情"]) {
        
        self.title = @"参加的人";

        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/activity/pationmanlist/activityid/%@",kBaseUrl,self.dictActivity[@"id"]]]]];
        
        
        
    }else if([currentTitle isEqualToString:@"参加的人"]){
        self.title = @"活动详情";
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/activity/detail/id/%@",kBaseUrl,self.dictActivity[@"id"]]]]];
        
    }else{
         [self.stack popBoardAnimated:YES];
    }
    
}



ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
}

ON_SIGNAL2(ActivityDetailBoard, signal){
    if ([signal is:ActivityDetailBoard.COLLECTION]) {
        
        if ([[self.dictActivity objectForKey:@"is_faved"] intValue] != 1) {
            BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apiactivity/addfav/",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"activityid",self.dictActivity[@"id"]);
            
            [request setStringEncoding:NSUTF8StringEncoding];
            
            printf("请求收藏");
            
            request.tag = 9527;
            
        }else{
            
            printf("请求取消收藏");
            
            BeeHTTPRequest* req = [self POST:[NSString stringWithFormat:@"%@/apiactivity/cancelfav/",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"activityid",self.dictActivity[@"id"]).PARAM(@"session_id",kUserInfo[@"session_id"]);
            
            req.tag = 9555;
            
//
//            
//              [request setStringEncoding:NSUTF8StringEncoding];
//            request.tag = 9555;
            
            
        }
        
     
    }
    else if ([signal is:ActivityDetailBoard.SHARE]) {
    }
    else if ([signal is:ActivityDetailBoard.ADD_IN]) {
        AddActivityBoard *board = [[AddActivityBoard alloc] init];
        board.dictActivity = self.dictActivity;
        [self presentViewController:[BeeUIStack stack:@"" firstBoard:board] animated:YES completion:nil];
    }
}

- (void)loadContent{
    
    
    _webView= [BeeUIWebView spawn];
    _webView.frame = CGRectMake(0, 0, self.viewWidth, self.viewHeight-(IOS7_OR_LATER?64:44));
    [self.view addSubview:_webView];
    
    NSString* url;
    
    if (self.isFromScroll) {
        
        url = self.webUrl;

    }else{
        
        url = [NSString stringWithFormat:@"%@/activity/detail/id/%@",kBaseUrl,self.dictActivity[@"id"]];
        
        
        if (self.dictActivity) {
            
            NSString* timeLine = [self.dictActivity objectForKey:@"timeline"];
            if ([timeLine intValue] == 3) { //活动已结束
               
                UIButton* btn = [[UIButton alloc]initWithFrame: CGRectMake(0, self.viewHeight-44-(IOS7_OR_LATER?64:44), self.viewWidth, 44)];
                btn.backgroundColor = [UIColor grayColor];
                [btn setTitle:@"活动已结束" forState:UIControlStateNormal];
                [btn setFont:[UIFont boldSystemFontOfSize:15]];
//                [self.view addSubview:btn];
//                [btn bringSubviewToFront:self.view];
                
            }else{
                BaseButton *btn = [BaseButton initBaseBtn:IMAGESTRING(@"btn_activity_in") highlight:IMAGESTRING(@"btn_activity_in_pre")];
                btn.frame = CGRectMake(0, self.viewHeight-44-(IOS7_OR_LATER?64:44), self.viewWidth, 44);
                [btn addSignal:ActivityDetailBoard.ADD_IN forControlEvents:UIControlEventTouchUpInside];
//                [self.view addSubview:btn];
//                [btn bringSubviewToFront:self.view];
            }
            
        }
        
        
    }
    
    _webView.url = url;
     _webView.delegate = self;

}

- (void)webViewDidFinishLoad:(UIWebView *)webView{

    
    NSString* nextUrl = [webView. request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"完成后的URL：%@",nextUrl);
    
    
    
    if (_couldChange) {
        currentUrl = webView.request.URL.absoluteString;
        if ([webView.request.URL.absoluteString isEqualToString:@"http://api.iheima.com/activity/detail/id/161"]) {
            
            
            
        }else if ([webView.request.URL.absoluteString isEqualToString:[NSString stringWithFormat:@"http://www.iheima.com/activity/pationmanlist/activityid/%@",self.dictActivity[@"id"]]]) {
            
            
            self.title = @"参加的人";
            
        }else{
            
            
            self.title = @"个人详情";
        }
        

    }
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    _couldChange = NO;
   
    
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    
    
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        _couldChange = YES;
    }
    
    
    NSString* nextUrl = [request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"打印整个URL:%@",nextUrl);
    
    
    
    
    
    NSArray* arr = [nextUrl componentsSeparatedByString:@"/"];
    NSLog(@"当前数组内元素个数:%d",arr.count);
    if (arr.count == 7) {
        
            if ([[arr objectAtIndex:4] isEqualToString:@"myhome"] ) {
                NSLog(@"该换页面了");
                
                [webView stopLoading];
                [self toNewUrlByOriginUrl:nextUrl];
                
                _afterAddingUrl = nextUrl;
                
               // isShoudToNew = NO;
            }
        }
   
    
    
    


    
    if([nextUrl componentsSeparatedByString:@"#"].count == 5){
        
        NSLog(@"整个URL：%@",nextUrl);
        
        [webView stopLoading];
        NSArray* ac = [nextUrl componentsSeparatedByString:@"#"];
        NSArray* arr = [[ac objectAtIndex:2] componentsSeparatedByString:@"&"];
        NSLog(@"----%@",[arr objectAtIndex:0]);
        NSLog(@"=====%@",[arr objectAtIndex:1]);
        
        //action
        _action =[[[arr objectAtIndex:0] componentsSeparatedByString:@"="] objectAtIndex:1];
        NSLog(@"动作：%@",[[[arr objectAtIndex:0] componentsSeparatedByString:@"="] objectAtIndex:1]);
        _id = [[[arr objectAtIndex:1] componentsSeparatedByString:@"="] objectAtIndex:1];
        NSLog(@"fid:%@",[[[arr objectAtIndex:1] componentsSeparatedByString:@"="] objectAtIndex:1]);
        
        if ([_action isEqualToString:@"addfriend"] && _id) {
            //发送 添加好友请求
            
            
            [self addFriendByFid:_id];
           // isShoudToNew = YES;
          
            
        }else if([_action isEqualToString:@"joinactivity"]){
            AddActivityBoard *board = [[AddActivityBoard alloc] init];
            board.dictActivity = self.dictActivity;
            [self presentViewController:[BeeUIStack stack:@"" firstBoard:board] animated:YES completion:nil];

        
        }
        
        
        
    }
    
    
    return YES;
}


- (void)toNewUrlByOriginUrl:(NSString*)originUrl{
    
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/myid/%@",originUrl,kUserInfo[@"uid"]]]]];
    
}


- (void)addFriendByFid:(NSString*)fuid{
    
    BeeHTTPRequest* request = [self POST:[NSString stringWithFormat:@"%@/apiuser/addfriend",kBaseUrl]].PARAM(@"fuid",fuid).PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"message",@"addFriend");
    
    request.tag = 8868;
    
    //[self POST:[NSString stringWithFormat:@"%@/apiuser/addfriend",kBaseUrl]].PARAM(@"uid",fuid).PARAM(@"fuid",kUserInfo[@"uid"]).PARAM(@"message",@"addFriend");
    
}

- (void)handleRequest:(BeeRequest *)request
{
    id json = [request.responseString mutableObjectFromJSONString];
    
    
    
    if(request.failed)
    {
        [[BeeUITipsCenter sharedInstance] dismissTips];
        NETWORK_ERROR
    }
    else if (request.succeed)
    {
        
        if ([json[@"status"] intValue] == 1) {
            switch (request.tag) {
                case 9555:
                {
                    [self.dictActivity setObject:@"0" forKey:@"is_faved"];
                    [self sendUISignal:BeeUIBoard.WILL_APPEAR];
                    [[BeeUITipsCenter sharedInstance] presentMessageTips:@"取消收藏成功"];
                    
                }
                    
                    break;
                case 9527:
                {
                    [self.dictActivity setObject:@"1" forKey:@"is_faved"];
                    [self sendUISignal:BeeUIBoard.WILL_APPEAR];
                    [[BeeUITipsCenter sharedInstance] presentMessageTips:@"收藏成功"];
                }
                    
                    break;
                case 8868:
                {
                    
                    UIAlertView* av = [[UIAlertView alloc]initWithTitle:@"添加好友成功" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:Nil, nil];
                                  [av show];
                    
                    if (_afterAddingUrl) {
                       [self toNewUrlByOriginUrl:_afterAddingUrl];
                    }else
                         NSLog(@"不存在 无法刷新");
                    
                    
                    
                    

                    
                }
                    break;
                default:
                    break;
                    
            
                    
            }

        }

        
        
        
    }

    
    
    
//    switch (request.tag) {
//        case 8868:
//            if(request.failed)
//            {
//                [[BeeUITipsCenter sharedInstance] dismissTips];
//                NETWORK_ERROR
//            }
//            else if (request.succeed)
//            {
//                
//                
//                UIAlertView* av = [[UIAlertView alloc]initWithTitle:@"添加好友成功" message:@"提示" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:Nil, nil];
//                [av show];
//
//                
//            }
//            break;
//        case 9527:
//            if(request.failed)
//            {
//                [[BeeUITipsCenter sharedInstance] dismissTips];
//                NETWORK_ERROR
//            }
//            else if (request.succeed)
//            {
//                
//                switch ([json[@"status"] intValue]) {
//                    case 1:
//                    {
//                        switch (request.tag) {
//                            case 9527:
//                            {
//                                [self.dictActivity setObject:@"1" forKey:@"is_faved"];
//                                [self sendUISignal:BeeUIBoard.WILL_APPEAR];
//                                [[BeeUITipsCenter sharedInstance] presentMessageTips:@"收藏成功"];
//                            }
//                                break;
//                                
//                           
//                        }
//                    }
//                }
//            }
//
//            break;
//            
//        case 9555:
//            
//        default:
//            break;
//    }
//    
//    
}







@end
